from AbstractClass.AbstractGetter import AbstractParser
import re, json

class Parser(AbstractParser):
    def __init__(self):
        super().__init__()

    def parse_single_weeks(self, week_range):
        # 匹配类似"1-18周"的格式
        match = re.search(r'(\d+)-(\d+)', week_range)
        match2 = re.search(r'(\d+)', week_range)
        odd_even = re.search(r'(单|双)', week_range)

        if match:
            start = int(match.group(1))
            end = int(match.group(2))

            if odd_even:
                weeks = []
                type_ = odd_even.group(1)
                for i in range(start, end + 1):
                    if (type_ == "单" and i % 2 == 1) or (type_ == "双" and i % 2 == 0):
                        weeks.append(i)
                return weeks
            else:
                return list(range(start, end + 1))
        elif match2:
            return [int(match2.group(1))]
        else:
            print("Invalid week range format. Please use the format 'x-y'.")
            return []

    def parse_weeks(self, data_str):
        weeks = []
        for item in data_str.split(','):
            weeks.extend(self.parse_single_weeks(item))
        return weeks

    def parse_sections(self, data_str):
        return self.parse_weeks(data_str)

    def get_data(self, original_data: dict, extra=None):
        data = original_data["data"]
        # 主处理逻辑
        result = []
        for course in data.get('kbList', []):
            course_info = {
                'name': course.get('kcmc', ''),
                'position': course.get('cdmc', ''),
                'teacher': course.get('xm', ''),
                'weeks': self.parse_weeks(course.get('zcd', '')),
                'day': int(course.get('xqj', 0)),
                'sections': self.parse_sections(course.get('jc', ''))
            }
            result.append(course_info)

        return result